package com.meetingshow.commu.actions;

import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

import javax.servlet.http.HttpServletResponse;

import net.sf.json.JSONArray;
import net.sf.json.JSONObject;

import org.apache.commons.lang.StringUtils;
import org.apache.log4j.Logger;
import org.apache.struts2.ServletActionContext;
import org.apache.struts2.convention.annotation.Action;
import org.apache.struts2.convention.annotation.Namespace;

import com.meetingshow.common.PageBean;
import com.meetingshow.common.base.actions.BaseAction;
import com.meetingshow.common.base.service.model.QueryResults;
import com.meetingshow.common.base.uiservice.exception.BaseUIServiceException;
import com.meetingshow.commu.jsonbean.AnswerJsonBean;
import com.meetingshow.commu.jsonbean.QuestJsonBean;
import com.meetingshow.commu.uiservice.IUIAnswerService;
import com.meetingshow.commu.uiservice.IUIQuestionService;
import com.meetingshow.commu.uiservice.model.AnswerQueryParasVO;
import com.meetingshow.commu.uiservice.model.AnswerVO;
import com.meetingshow.commu.uiservice.model.QuestionQueryParasVO;
import com.meetingshow.commu.uiservice.model.QuestionVO;
import com.meetingshow.utils.JSONUtils;
import com.meetingshow.utils.UIServiceFactory;

@Namespace("/commu")
public class CommuAction extends BaseAction {

    private final static Logger logger = Logger.getLogger(CommuAction.class);

    /**
     * 
     */
    private static final long serialVersionUID = 4074334327923987803L;

    private String param;

    @Action(value = "ask")
    public String saveQuestion() {
        HttpServletResponse response = ServletActionContext.getResponse();
        try {
            if (StringUtils.isBlank(param)) {
                response.getWriter().write(buildErrorJson("-1", "No parameter."));
                return null;
            }
            JSONObject jObj = JSONObject.fromObject(param);
            QuestJsonBean qJsonBean = (QuestJsonBean) JSONObject.toBean(jObj,
                    QuestJsonBean.class);

            QuestionVO questionVO = JSONUtils.toQuestionVO(qJsonBean);
            IUIQuestionService uiQuestionService = UIServiceFactory
                    .getUIQuestionService();
            Integer questionId = uiQuestionService.saveQuestion(questionVO);
            QuestJsonBean retJsonBean = new QuestJsonBean();
            if (questionId != null)
                retJsonBean.setQuestionId(String.valueOf(questionId));
            response.getWriter().write(JSONObject.fromObject(retJsonBean).toString());
        } catch (Exception e) {
            logger.error(e.getMessage(), e);
            try {
                if (e instanceof BaseUIServiceException) {
                    response.getWriter().write(buildErrorJson("-1", e.getMessage()));
                } else {
                    response.getWriter().write(buildErrorJson("-1", "SaveQuestion error."));
                }
            } catch (IOException ex) {
                logger.error(ex.getMessage(), ex);
            }
        }
        return null;
    }

    @Action(value = "answer")
    public String saveAnswer() {
        HttpServletResponse response = ServletActionContext.getResponse();
        try {
            if (StringUtils.isBlank(param)) {
                response.getWriter().write(buildErrorJson("-1", "No parameter."));
                return null;
            }
            JSONObject jObj = JSONObject.fromObject(param);
            AnswerJsonBean aJsonBean = (AnswerJsonBean) JSONObject.toBean(jObj,
                    AnswerJsonBean.class);

            AnswerVO answerVO = JSONUtils.toAnswerVO(aJsonBean);

            IUIAnswerService uiAnswerService = UIServiceFactory
                    .getUIAnswerService();
            Integer answerId = uiAnswerService.saveAnswer(answerVO);
            AnswerJsonBean retJsonBean = new AnswerJsonBean();
            if (answerId != null)
                retJsonBean.setAnswerId(String.valueOf(answerId));
            response.getWriter().write(JSONObject.fromObject(retJsonBean).toString());
        } catch (Exception e) {
            logger.error(e.getMessage(), e);
            try {
                if (e instanceof BaseUIServiceException) {
                    response.getWriter().write(buildErrorJson("-1", e.getMessage()));
                } else {
                    response.getWriter().write(buildErrorJson("-1", "SaveAnswer error."));
                }
            } catch (IOException ex) {
                logger.error(ex.getMessage(), ex);
            }
        }
        return null;
    }

    @Action(value = "getQ")
    public String getQuestions() {
        HttpServletResponse response = ServletActionContext.getResponse();
        try {
            if (StringUtils.isBlank(param)) {
                response.getWriter().write(buildErrorJson("-1", "No parameter."));
                return null;
            }
            JSONObject jObj = JSONObject.fromObject(param);
            QuestJsonBean qJsonBean = (QuestJsonBean) JSONObject.toBean(jObj,
                    QuestJsonBean.class);

            QuestionQueryParasVO questionQueryParasVO = new QuestionQueryParasVO();
            questionQueryParasVO.setTopicId_e(String.valueOf(qJsonBean
                    .getTopicId()));
            questionQueryParasVO.setFirstresultno(String
                    .valueOf(PageBean.SINGLE_PAGE_CUR_PAGE - 1));
            questionQueryParasVO.setResultspergroup(String
                    .valueOf(PageBean.SINGLE_PAGE_ROWS_MAX));

            IUIQuestionService uiQuestionService = UIServiceFactory
                    .getUIQuestionService();
            IUIAnswerService uianAnswerService = UIServiceFactory.getUIAnswerService();
            
            QueryResults<QuestionVO> qQueryResults = uiQuestionService
                    .queryQuestion(questionQueryParasVO);

            if (QueryResults.resultsListNotNull(qQueryResults)) {
                List<QuestJsonBean> questionList = new ArrayList<QuestJsonBean>();

                for (QuestionVO questionVO : qQueryResults.getResultList()) {
                    QuestJsonBean retJsonBean = JSONUtils.toQuestJsonBean(questionVO);

                    //查询回答
                    AnswerQueryParasVO answerQueryParasVO = new AnswerQueryParasVO();
                    answerQueryParasVO.setQuestionId_e(String.valueOf(questionVO.getQuestionId()));
                    
                    QueryResults<AnswerVO> aQueryResults = uianAnswerService.queryAnswer(answerQueryParasVO);
                    
                    if (QueryResults.resultsListNotNull(aQueryResults)) {
                        List<AnswerJsonBean> answerList = new ArrayList<AnswerJsonBean>();
                        for (AnswerVO answerVO : aQueryResults.getResultList()) {
                            AnswerJsonBean answerJsonBean = JSONUtils.toAnswerJsonBean(answerVO);
                            answerList.add(answerJsonBean);
                        }
                        retJsonBean.setAnswers(answerList);
                    }
                    questionList.add(retJsonBean);
                }
                
                response.getWriter().write(JSONArray.fromObject(questionList).toString());
            }
        } catch (Exception e) {
            logger.error(e.getMessage(), e);
            try {
                if (e instanceof BaseUIServiceException) {
                    response.getWriter().write(buildErrorJson("-1", e.getMessage()));
                } else {
                    response.getWriter().write(buildErrorJson("-1", "GetQuestions error."));
                }
            } catch (IOException ex) {
                logger.error(ex.getMessage(), ex);
            }
        }
        return null;
    }

    public String getParam() {
        return param;
    }

    public void setParam(String param) {
        this.param = param;
    }
}
